package com.zz.servlet3.servlet;

import com.zz.servlet3.listener.CustomAsyncListener;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "async", urlPatterns = "/async", asyncSupported = true)
public class AsyncServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("hello async");

        final AsyncContext actx = req.startAsync();
        actx.addListener(new CustomAsyncListener());
        actx.start(() -> {
            try {
                long startTime = System.currentTimeMillis();
                Thread.sleep(2 * 1000);
                actx.getResponse().getWriter().println("\r\nthread sleep 2s");
                System.out.println("consume time:" + (System.currentTimeMillis() - startTime));
                actx.complete();
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
        });
    }
}
